//
//  SearchRecordView.m
//  PearRich
//
//  Created by Jinniu on 2020/3/13.
//  Copyright © 2020 谢黎鹏. All rights reserved.
//

#import "SearchRecordView.h"
#import "SearchRecordCell.h"
@interface SearchRecordView()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,retain)UITableView * myTab;
@property(nonatomic,retain)NSMutableArray * dataArr;
@end
@implementation SearchRecordView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createUI:frame];
    }
    return self;
}
-(void)createUI:(CGRect)frame{
    self.dataArr = [NSMutableArray new];
        
    self.myTab = [[UITableView alloc]initWithFrame:Frame(0, 0, IPHONE_WIDTH, frame.size.height) style:UITableViewStyleGrouped];
    _myTab.delegate = self;
    _myTab.dataSource = self;
    [self addSubview:self.myTab];
    
    [self getData];
}
-(void)getData{
    NSArray * arr = [SearchRecordModel bg_find:SearchRecordTab limit:0 orderBy:@"bg_createTime" desc:YES];
    [_dataArr addObjectsFromArray:arr];
    [self.myTab reloadData];
}
#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[SearchRecordCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    SearchRecordModel * mo = self.dataArr[indexPath.row];
    cell.model = mo;
    cell.delBlock = ^{
        NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(bg_primaryKey),mo.bg_id];
        [SearchRecordModel bg_delete:SearchRecordTab where:where];
        [self.dataArr removeAllObjects];
        [self getData];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchRecordModel * mo = self.dataArr[indexPath.row];
    if (self.selBlock) {
        self.selBlock(mo.name);
    }
}
@end
